package com.dao;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.base.BaseDao;
import com.bean.RoleInfo;
import com.bean.RulerInfo;
import com.bean.RulerMethod;
import com.bean.RulerRole;
import com.util.GUtil;

public class RoleDao extends BaseDao {

	private static final Logger log = LoggerFactory
			.getLogger(ParkManagerDao.class);

	public RoleInfo get(Integer id) throws Exception{
		Session session=this.getSession();
		return (RoleInfo) session.get(RoleInfo.class, id);
	}
	public List findByProperty(String propertyName, Object value) {
		log.debug("finding RoleInfo instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from RoleInfo  as model where model."
					+ propertyName + "= ?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	@SuppressWarnings("unchecked")
	public List<RoleInfo> query(RoleInfo roleInfo) throws Exception{
		Session session=this.getSession();
		String hql="From RoleInfo Where status!=0"; // and flag>0
		if(roleInfo!=null && roleInfo.getRoleName()!=null && !roleInfo.getRoleName().trim().equals("")){
			hql+=" and roleName like '%"+roleInfo.getRoleName().trim()+"%'";
		}

		Query query = session.createQuery(hql);
		List<RoleInfo> list = (List<RoleInfo>)query.list();
		return list;
	}
	/**
	 * 根据角色ID获取此角色的权限
	 * <p>Title: beforeUpdate</p>
	 * <p>Description: </p>
	 * @param id
	 * @return  设置完成后的所有菜单list
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public List<RulerInfo> beforeUpdate(int id) throws Exception{

		Session session=this.getSession();
		String hql = "From RulerInfo where";
		List<RulerMethod> ruleMethodList ;

		//获取所有菜单列表
		List<RulerInfo>  rulerList;
		hql = "From RulerInfo where status=1 ";
		Query query = session.createQuery(hql);
		rulerList = query.list();
		// 获取菜单的 method

		//设定roleid=id的权限checked = true;
		RulerRole r;
		hql = "From RulerRole where roleId=?";
		List<RulerRole> rulerRoleList = new ArrayList<RulerRole>();
		query = session.createQuery(hql);
		query.setParameter(0, id);
		rulerRoleList = query.list();
		for(RulerRole rr : rulerRoleList){
			for( RulerInfo ri : rulerList){
				if(ri.getRulerid()==rr.getRulerId() && rr.getRulerWord()!=null ){
//					ri.setCheckedMethods(rr.getRulerWord());
				}
			}
		}

		return rulerList;

	}

	public String add(RoleInfo roleInfo, List<RulerInfo> rulerList) throws Exception{
		Session session = this.getSession();
		Long t1 = System.currentTimeMillis();
		//save rulerinfo
		Timestamp lastUpdate = new Timestamp(System.currentTimeMillis());
		roleInfo.setLastUpdate(lastUpdate);
		if(roleInfo.getStatus()==null)
			roleInfo.setStatus(1);
		session.save(roleInfo);
		session.flush();

		//insert new RulerRole
		RulerRole rulerRole;
		for(RulerInfo r1 : rulerList){
			if(r1==null)
				continue;
			rulerRole = new RulerRole();
			rulerRole.setRulerId(r1.getRulerid());
			rulerRole.setRoleId(roleInfo.getRoleId());
			List<RulerMethod> list2 = r1.getMethods();
			String methods="" ;
			if(list2!=null){
				for(RulerMethod rm :list2){
					if(rm==null)
						continue;
					methods += rm.getMethod() + ";"; 
				}
			}
			rulerRole.setRulerWord(methods);

			rulerRole.setLastUpdate(lastUpdate);
			rulerRole.setStatus(1);
			session.save(rulerRole);
		}
		session.flush();
		Long t2 = System.currentTimeMillis();
		log.info(" RoleDao.update takes "+(t2-t1)+"ms");
		return GUtil.SUCCESS;

	}

	public String update(RoleInfo roleInfo, List<RulerInfo> rulerList)  throws Exception{
		Session session = this.getSession();

		Long t1 = System.currentTimeMillis();

		//update rulerinfo
		Timestamp lastUpdate = new Timestamp(System.currentTimeMillis());
		roleInfo.setLastUpdate(lastUpdate);
		roleInfo.setStatus(1);
		session.update(roleInfo);
		session.flush();
		log.info("roleInfo.roleName="+roleInfo.getRoleName());

		//clear the old  RulerRole
		session.createQuery("delete RulerRole r where r.roleId="+roleInfo.getRoleId()+" ").executeUpdate();

		//insert new RulerRole
		RulerRole rulerRole;
		for(RulerInfo r1 : rulerList){
			if(r1==null)
				continue;
			rulerRole = new RulerRole();
			rulerRole.setRulerId(r1.getRulerid());
			rulerRole.setRoleId(roleInfo.getRoleId());
			List<RulerMethod> list2 = r1.getMethods();
			String methods="" ;
			if(list2!=null){
				for(RulerMethod rm :list2){
					if(rm==null)
						continue;
					methods += rm.getMethod() + ";"; 
				}
			}
			rulerRole.setRulerWord(methods);

			rulerRole.setLastUpdate(lastUpdate);
			rulerRole.setStatus(1);
			session.save(rulerRole);
		}
		session.flush();
		Long t2 = System.currentTimeMillis();
		log.info(" RoleDao.update takes "+(t2-t1)+"ms");
		return GUtil.SUCCESS;
	}

	public String update(RoleInfo roleInfo,String rightString, List<RulerInfo> rulerList) throws Exception{

		if(rulerList!=null)
			return update(roleInfo, rulerList);// new method
		else
			return GUtil.FAILE;
	}
	
	public String delete(int id, Integer flag) throws Exception{
		Session session = this.getSession();

		RoleInfo roleInfo = (RoleInfo) session.get(RoleInfo.class, id);
		if(flag==null)
			session.delete(roleInfo);
		else{
			roleInfo.setLastUpdate(new Timestamp(System.currentTimeMillis()));
			roleInfo.setStatus(flag);
			session.update(roleInfo);
		}
		return GUtil.SUCCESS;
	}
	@SuppressWarnings("unchecked")
	public String beforeAdd() throws Exception{
		Session session=this.getSession();
		List<RulerInfo> list;
		StringBuffer sb = new StringBuffer();
		sb.append("{");
		sb.append("array:[");
		list=session.createQuery("From RulerInfo").list();
		for(int i=0;i<list.size();i++){
			if(list.get(i).getLevel()==1){
				sb.append("{id:").append(list.get(i).getRulerid()).append(",");
				sb.append("pId:").append(0).append(",");
				sb.append("name:'").append(list.get(i).getRulerName()).append("',");
				//	sb.append("rulerWord:'").append("uvid").append("',");
				sb.append("open:").append("true");

				sb.append("}");
				for(int k=0;k<list.size();k++){
					if(list.get(k).getLevel()==2 && list.get(k).getManager() == list.get(i).getRulerid()){
						sb.append(",{id:").append(list.get(k).getRulerid()).append(",");
						sb.append("pId:" ).append(list.get(k).getManager()).append(",");
						sb.append("name:'").append(list.get(k).getRulerName()).append("'");
						sb.append("}");
					}	
				}
				if(i<list.size()){
					sb.append(",");
				}
			}
		}
		sb.append("]}");
		return sb.toString();
	}
	public String add(RoleInfo roleInfo,String rightString, List<RulerInfo> rulerList) throws Exception{
		
		return this.add(roleInfo, rulerList);
		
		//blow id delted
		/*
		Session session = this.getSession();
		String [] array = rightString.split(";");
		RulerRole rulerRole;
		Timestamp lastUpdate = new Timestamp(System.currentTimeMillis());
		roleInfo.setLastUpdate(lastUpdate);
		roleInfo.setStatus(1);
		session.save(roleInfo);
		if(rightString!=null && rightString.length()>0 && roleInfo.getRoleId()!=null)
		{
			//	roleInfo=(RoleInfo) session.createQuery("from RoleInfo r where r.lastUpdate='"+roleInfo.getLastUpdate()+"' and r.roleName='"+roleInfo.getRoleName()+"'").uniqueResult();
			for(int i=0;i<array.length;i++){
				rulerRole = new RulerRole();
				rulerRole.setRoleId(roleInfo.getRoleId());
				rulerRole.setRulerId(Integer.parseInt(array[i].split(",")[0]));
				if(array[i].split(",").length>=2){
					String roleWord = array[i].split(",")[1];
					if(!roleWord.equals("undefined"))
						rulerRole.setRulerWord(roleWord);
					else
						rulerRole.setRulerWord("");
				}else
					rulerRole.setRulerWord("");
				rulerRole.setLastUpdate(lastUpdate);
				rulerRole.setStatus(1);
				session.save(rulerRole);
			}
		}
		return GUtil.SUCCESS;
		*/
	}
}
